//
//  _HACTecNodeVolume.m
//  HStockCharts
//
//  Created by Hotacool on 2018/9/27.
//

#import "_HACTecNodeVolume.h"
#import "HACLineChartDataSet.h"
#import "HACPointEntry.h"
#import "HACGradientWave.h"
#import "HACBrushCandle.h"

static const CGFloat kItemSpacing = 2.0;
@interface _HACTecNodeVolume ()
/** k线数据 */
@property (nonatomic, copy) NSArray *kLineData;
/** 画柱形图数据 */
@property (nonatomic, strong) NSMutableArray *rectDrawingData;
/** 画笔 */
@property (nonatomic, strong) HACBrushCandle *candleBrush;
@end

@implementation _HACTecNodeVolume

- (void)setUp {
    [super setUp];
    self.xAxisCount = 3;
    self.yAxisCount = 5;
    self.pointRect = CGRectZero;
    self.singleWidth = 1.0;
    self.itemsSpace = kItemSpacing;
    self.isSoildFill = YES;// 默认实心
    
    _candleBrush = [[HACBrushCandle alloc] initWithDataProvider:self];
}

- (void)removeNode {
    [super removeNode];
    [self.candleBrush removeBrush];
}

- (void)setData:(HACChartData *)data {
    //K线数据
    _kLineData = [data dataSetWithLabel:HACKLineViewDataLabel].values;
    if (!_kLineData) {//分时数据
        _kLineData = [data dataSetWithLabel:HACTimeLineViewDataLabel].values;
    }
    HACChartDataSet *tmp = [data dataSetWithLabel:HACBasicDataLabel];
    self.basicInfoData = tmp?(HACBasicInfoEntry*)tmp.values.firstObject:nil;
    
    self.startIndex = MAX(0, self.actualCount - self.visualCount);
    self.endIndex = MAX(self.visualCount, self.actualCount - 1);

    [super setData:data];
}

- (CGFloat)maxContentWidth {
    return MAX(self.actualCount * self.singleWidth , [super maxContentWidth]);
}

- (void)updateFrame {
    self.pointRect = self.relativeFrame;
    self.singleWidth = FormatValueWithRemain(self.relativeFrame.size.width / (self.visualCount), 3);// 可见数即visualCount
    if (self.singleWidth > kItemSpacing + 0.5) {
        self.itemsSpace = kItemSpacing;
    } else {
        CGFloat d = self.singleWidth - 0.5;
        if (d > 0) {
            self.itemsSpace = d;
        } else {
            self.itemsSpace = 0;
        }
    }
}

- (void)setNeedsDisplay {
    [super setNeedsDisplay];
    if (self.hostLayer) {
        if (self.maxValue == 0 && self.minValue ==0) {
            //容错，无成交量不显示
            [self.candleBrush removeBrush];
        } else {
            [self.candleBrush drawInLayer:self.hostLayer inRect:self.relativeFrame];
        }
    }
}

- (NSInteger)actualCount {
    return _kLineData?_kLineData.count:0;
}

#pragma mark - provider
- (NSArray <HACAxisComponents *>*)xAxisDatasInRect:(CGRect)rect {
    NSInteger axisCount = self.xAxisCount;
    if (axisCount <= 0)
        return nil;
    
    NSMutableArray *xAxisDrawingData = [NSMutableArray array];
    // 从下往上
    for (int index = 0; index < axisCount; index++) {
        HACAxisComponents *axisItem = [[HACAxisComponents alloc] init];
        axisItem.index = index;
        axisItem.lineBolder = 0.5;
        axisItem.axisType = DrawingAxisTypeX;
        axisItem.queueLocation = CGQueueLocation(index, axisCount);
        CGFloat y = [self calculatorYForValue:index min:0 max:axisCount - 1 inRect:self.relativeFrame];
        [xAxisDrawingData addObject:axisItem];
        
        // x轴左边的默认值，按照最大值等分
        axisItem.text = [self stringForAxisTextItem:axisItem];
        if (!axisItem.text) {
            CGFloat yValue = self.minValue + (ABS(self.maxValue - self.minValue) / (axisCount - 1)) * index;
            long digits = self.basicInfoData.hand<=0?100:self.basicInfoData.hand;//股数转手数单位
            NSString *str = [HACChartUtils transferVolumeToStandardString:yValue/digits];
            axisItem.text = str;
            axisItem.textFont = self.leftAxis.textFont;
        }
        
        CGSize textSize = [axisItem.text sizeWithAttributes:@{NSFontAttributeName : axisItem.textFont}];
        CGRect frame = CGRectMake(CGRectGetMinX(rect)+7, y, textSize.width , textSize.height);
        if (axisItem.queueLocation == QueueLocationHead) {
            // 最下面一个下坐标对其线的位置
            frame.origin.y -= textSize.height;
        } else if (axisItem.queueLocation == QueueLocationTrail) {
            // 最上面一个上坐标对其线的位置
        } else {
            frame.origin.y -= textSize.height / 2; // 中间的跟线居中对齐
            axisItem.text = @"";
            axisItem.extText = @"";
            if (index == axisCount/2) {
                axisItem.dashLengths = @[@2.0, @4.0];//中间线为开盘价，虚线
                axisItem.lineBolder = 1;
            }
        }
        axisItem.textFrame = frame;
        axisItem.extText = nil;
        axisItem.extTextFrame = CGRectZero;
        CGLine line;
        line = CGLineMake(self.relativeFrame.origin.x, y, CGRectGetMaxX(self.relativeFrame), y);
        axisItem.line = line;
        axisItem.lineColor = self.leftAxis.lineColor?:axisItem.lineColor;
    }
    return xAxisDrawingData;
}

- (NSArray *)rectDatasInRect:(CGRect)rect {
    if (self.actualCount == 0) {
        return nil;
    }
    
    NSMutableArray *rectDrawingData = [NSMutableArray array];
    CGFloat x = 0.0, y = 0.0;
    id pointData, lastData;
    for (NSInteger i = self.startIndex; i <= self.endIndex && i < self.actualCount; i++) {
        pointData = self.kLineData[i];
        HACRectComponents *rectItem = [[HACRectComponents alloc] init];
        rectItem.isSoildFill = self.isSoildFill;
        //偏移，转化到0~visualCount范围中
        NSInteger idx = [self relativeIdxFromIndex:i];
        x = [self xPointForIndex:idx inRect:self.pointRect];
        CGFloat value = [self rectValueForItem:pointData];
        if (value != 0) {//成交量为0，不显示
            y = [self calculatorYForValue:value min:self.minValue max:self.maxValue inRect:self.pointRect];
            rectItem.pillarRect = CGRectMake(x + self.itemsSpace/2, y, self.singleWidth - self.itemsSpace, CGRectGetMaxY(self.pointRect) - y);// y坐标从上往下
        }
        rectItem.valueType = [self calculatorValueType:pointData lastData:lastData];
        rectItem.lineColor = [self colorWithValueType:rectItem.valueType];
        rectItem.center = CGRectGetMidX(rectItem.pillarRect);
        [rectDrawingData addObject:rectItem];
        lastData = pointData;
        if ([pointData isKindOfClass:[HACKLineEntry class]]) {
            if (((HACKLineEntry*)pointData).trendRate == 0) {
                ((HACKLineEntry*)pointData).trendRate = (rectItem.valueType == DrawingDownValue)? -1:1;
            }
        } else if ([pointData isKindOfClass:[HACTimeLineEntry class]]) {
            if (((HACTimeLineEntry*)pointData).trendRate == 0) {
                ((HACTimeLineEntry*)pointData).trendRate = (rectItem.valueType == DrawingDownValue)? -1:1;
            }
        }
    }
    
    return rectDrawingData;
}

- (CGFloat)rectValueForItem:(id)data {
    if ([data isKindOfClass:[HACKLineEntry class]]) {
        return ((HACKLineEntry*)data).volume;
    } else if ([data isKindOfClass:[HACTimeLineEntry class]]) {
        return ((HACTimeLineEntry*)data).volume;
    }
    return 0;
}

// 计算最大，最小值
- (void)calculateLimitValue {
    CGFloat max = FLT_MIN;
    CGFloat min = FLT_MAX;
    CGFloat value;
    
    for (NSInteger i = self.startIndex; i <= self.endIndex && i < self.actualCount; i++) {
        id model = self.kLineData[i];
        
        value = [self maxValueForData:model];
        if (value != kDrawingInvaildValue && value > max) {
            max = value;
        }
        
        value = [self minValueForData:model];
        if (value != kDrawingInvaildValue && value < min) {
            min = value;
        }
    }
    self.maxValue = (max == FLT_MIN) ? .0 : max;
    self.minValue = (min == FLT_MAX) ? .0 : min;
}

- (CGFloat)maxValueForData:(HACKLineEntry *)data {
    return [self rectValueForItem:data];
}

- (CGFloat)minValueForData:(HACKLineEntry *)data {
    return 0;
}

- (DrawingValueType)calculatorValueType:(HACKLineEntry *)currentData lastData:(HACKLineEntry *)prePointData {
    if ([currentData isKindOfClass:[HACKLineEntry class]]) {
        if (currentData.closePrice > currentData.openPrice)
            return DrawingUpValue;
        else if (currentData.closePrice < currentData.openPrice)
            return DrawingDownValue;
        else {// 如果收盘价＝开盘价 ，根据昨收价判断
            if (currentData.closePrice > prePointData.closePrice)
                return DrawingUpValue;
            else if (currentData.closePrice < prePointData.closePrice)
                return DrawingDownValue;
            else // 如果跟昨收价还相同，保持前一天一样的逻辑
                return (DrawingValueType)prePointData.closePrice >= prePointData.openPrice;
        }
    } else if ([currentData isKindOfClass:[HACTimeLineEntry class]]) {
        HACTimeLineEntry *data = (HACTimeLineEntry *)currentData;
        HACTimeLineEntry *predata = (HACTimeLineEntry *)prePointData;
        if (data.newprice > predata.newprice) {
            return DrawingUpValue;
        } else if (data.newprice < predata.newprice) {
            return DrawingDownValue;
        } else {
            return DrawingEqualValue;
        }
    }
    return DrawingUpValue;
}

- (HACChartDataEntry*)dataAtChartForIndex:(NSUInteger)focusIndex {
    HACChartDataEntry *indexData = [super dataAtChartForIndex:focusIndex];
    if (self.kLineData && focusIndex < self.kLineData.count) {
        indexData = self.kLineData[focusIndex];
    }
    return indexData;
}

- (UIColor *)colorWithValueType:(DrawingValueType)valueType {
    UIColor *color = RGB_HEX(0xf83745);//等于时为DrawingUpValue
    switch (valueType) {
        case DrawingDownValue:
            color = RGB_HEX(0x5ba245);
            break;
        case DrawingUpValue:
            color = RGB_HEX(0xf83745);
            break;
        default:
            break;
    }
    
    return color;
}
@end
